﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Forms;
using MM.Common.Base;
using System.Diagnostics;
using System.Runtime.InteropServices;
using System.Threading;
using System.Globalization;
using MM.Commmon.UI;
using System.Text;
using MM.Common.DBBase;
using System.Configuration;
using DevExpress.XtraEditors;
using DevExpress.Skins;
using DevExpress.LookAndFeel;
using System.IO;

namespace MMTJ
{
    static class Program
    {
        private const int WS_SHOWNORMAL = 1;
        /// <summary>
        /// 应用程序的主入口点。
        /// </summary>
        [STAThread]
        static void Main()
        {
            string[] commandLineArgs = Environment.GetCommandLineArgs();
            if (commandLineArgs.Length >= 2)
            {
                SystemInfo.SystemCode = commandLineArgs[1];
            }
            else
            {
                SystemInfo.SystemCode = "PEIS";
            }
            SystemInfo.RunPath = Directory.GetCurrentDirectory()+"\\";
            if (ExistRunningInstance())
            {
                Environment.Exit(1);
            }
            else
            {
                Application.EnableVisualStyles();
                Application.SetCompatibleTextRenderingDefault(false);
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("zh-CHS");
                Thread.CurrentThread.CurrentCulture = new CultureInfo("zh-CN");
                LoadUI.ShowLoad();
                LoadUI.Guage("正在登录......", 5);
                Logger logger = new Logger("FrmRibbonMain:Init");
                logger.Info("系统初始化");
                long ticks = DateTime.Now.Ticks;
                string dbname = ConfigurationManager.AppSettings.Get("DataBase").ToUpper();
                if (dbname == null)
                {
                    dbname = "ORACLE";
                }
                SystemInfo.SetSystemInfo(dbname);
                LoadUI.Guage("正在尝试连接数据库......", 10);
                logger.Info("正在尝试连接数据库");
                string datasource = "";
                if (!GetPublicInfo(ref datasource))
                {
                    XtraMessageBox.Show("获取基本信息不成功！", "出错", MessageBoxButtons.OK, MessageBoxIcon.Question);
                    logger.Info("获取基本信息不成功");
                    Application.Exit();
                }
                else
                {
                    FrmRibbonMain main;
                    if (dbname == "REMOTE_ORACLE")
                    {
                        datasource = datasource + ";NODE=" + SystemInfo.ComputerID;
                    }
                    LoadUI.Guage("开始尝试连接数据库......", 40);
                    if (DataBase_Connect(datasource))
                    {
                        logger.Info("数据库连接成功");
                        LoadUI.Guage("数据库连接成功", 0x2d);
                        BaseDataHelper.IsNewComputer();
                    }
                    else
                    {
                        XtraMessageBox.Show("数据库连接不成功！", "出错", MessageBoxButtons.OK, MessageBoxIcon.Question);
                        logger.Info("数据库连接不成功");
                        Application.Exit();
                        return;
                    }
                    do
                    {
                        FrmXLogin login = new FrmXLogin(datasource);
                        if (!SkinManager.AllowFormSkins)
                        {
                            LookAndFeelHelper.ForceDefaultLookAndFeelChanged();
                            SkinManager.EnableFormSkins();
                        }
                        login.ShowDialog();
                        if (!login.DialogResult.Equals(DialogResult.OK))
                        {
                            break;
                        }
                        login.Close();
                        login.Dispose();
                        LoadUI.ShowLoad();
                        LoadUI.Guage("正在登录......", 5);
                        LoadUI.Guage("开始初始化主窗体......", 50);
                        logger.Info("开始初始化主界面......");
                        main = new FrmRibbonMain();
                        if (ExistRunningInstance())
                        {
                            Environment.Exit(1);
                            break;
                        }
                        main.Init();
                        LoadUI.Guage("初始化主界面完成", 100);
                        logger.Info("初始化完成");
                        LoadUI.CloseLoad();
                        Application.Run(main);
                    }
                    while (main.DialogResult.Equals(DialogResult.Retry));
                    Application.Exit();
                }
            }
        }

        public static bool GetPublicInfo(ref string datasource)
        {
            string key = "mxhly207";
            SymmCrypto crypto = new SymmCrypto(SymmCrypto.SymmProvEnum.A);
            String str = crypto.Encrypting("sa", key);
            try
            {
                LoadUI.Guage("正在尝试取单位名称......", 15);
                string source = ConfigurationManager.AppSettings.Get("UserName");
                SystemInfo.OrgHeadName = source;


                LoadUI.Guage("正在尝试取数据库口令......", 0x19);
                source = ConfigurationManager.AppSettings.Get("DBPassWord");

                string str5 = crypto.Decrypting(source, key);
                datasource = ConfigurationManager.AppSettings.Get("DataSource");
                
                datasource = datasource + "Password="+ str5;
                LoadUI.Guage("正在认证授权......", 0x23);
                source = ConfigurationManager.AppSettings.Get("LastDate");
                SystemInfo.LastDate = Convert.ToDateTime(crypto.Decrypting(source, key));
                if (DateTime.Now > SystemInfo.LastDate)
                {
                    XtraMessageBox.Show("系统已经过期, 请与供应商联系！", "提示");
                    return false;
                }
                return true;
            }
            catch
            {
                LoadUI.CloseLoad();
                return false;
            }
        }


        private static bool DataBase_Connect(string datasource)
        {
            bool flag = true;
            try
            {
                if (!SystemInfo.DbData.OpenConnect(datasource))
                {
                    LoadUI.CloseLoad();
                    MessageBox.Show(SystemInfo.DbData.ErrorMessage, "出错");
                    return false;
                }
                string commandtext = "SELECT COUNT(*) FROM MXHLY_SYS_COMPUTER WHERE COMPUTER_CODE = @node";
                object obj2 = -1;
                DataParamCol parms = new DataParamCol(new DataParam[] { new InputDataParam("node", SystemInfo.ComputerID) });
                SystemInfo.DbData.ExecuteScalar(commandtext, parms, ref obj2);
                if (Convert.ToInt16(obj2) != 1)
                {
                    commandtext = "INSERT INTO MXHLY_SYS_COMPUTER (COMPUTER_CODE ,COMPUTER_NAME ,IP) VALUES (@code ,@cname ,@ip)";
                    parms = new DataParamCol();
                    parms.AddBatch(new object[] { "code", SystemInfo.ComputerID, "cname", SystemInfo.ComputerName, "ip", SystemInfo.ComputerIp });
                    SystemInfo.DbData.ExecuteSql(commandtext, parms);
                }
                SystemInfo.DbData.ChangeSQLTableOrder = ConfigFunction.GetComputerConfig("ChangeSQLTableOrder", " ", "加入数据改变表的序号");
            }
            catch (Exception exception)
            {
                LoadUI.CloseLoad();
                MessageBox.Show(exception.Message, "出错");
                flag = false;
            }
            return flag;
        }

        public static bool ExistRunningInstance()
        {
            bool flag = false;
            string[] commandLineArgs = Environment.GetCommandLineArgs();
            try
            {
                Process currentProcess = Process.GetCurrentProcess();
                foreach (Process process2 in Process.GetProcessesByName(currentProcess.ProcessName))
                {
                    string mainWindowTitle = process2.MainWindowTitle;
                    if ((process2.Id != currentProcess.Id) && (mainWindowTitle.IndexOf("MXHLY --- [" + commandLineArgs[1] + "]") == 0))
                    {
                        ShowWindowAsync(process2.MainWindowHandle, 1);
                        SetForegroundWindow(process2.MainWindowHandle);
                        flag = true;
                    }
                }
            }
            catch
            {
                flag = false;
            }
            return flag;
        }

        [DllImport("User32.dll")]
        public static extern void SetForegroundWindow(IntPtr hwnd);
        [DllImport("User32.dll")]
        private static extern bool ShowWindowAsync(IntPtr hWnd, int cmdShow);
    }
}
